/// 认证Provider
/// 管理用户认证状态
library;

import 'package:flutter/material.dart';
import 'package:chat_project/models/user_model.dart';
import 'package:chat_project/services/api_service.dart';
import 'package:chat_project/services/storage_service.dart';

enum AuthStatus {
  initial,
  authenticating,
  authenticated,
  unauthenticated,
  error
}

class AuthProvider with ChangeNotifier {
  final ApiService _apiService = ApiService();
  final StorageService _storageService = StorageService();

  AuthStatus _status = AuthStatus.initial;
  User? _user;
  String? _error;

  // Getters
  AuthStatus get status => _status;
  User? get user => _user;
  String? get error => _error;
  bool get isAuthenticated => _status == AuthStatus.authenticated;

  // 初始化
  Future<void> init() async {
    try {
      final isLoggedIn = await _storageService.isLoggedIn();
      
      if (isLoggedIn) {
        await _loadUser();
      } else {
        _status = AuthStatus.unauthenticated;
        notifyListeners();
      }
    } catch (e) {
      _status = AuthStatus.unauthenticated;
      notifyListeners();
    }
  }
  
  // 加载用户信息
  Future<void> _loadUser() async {
    try {
      _status = AuthStatus.authenticating;
      notifyListeners();
      
      // 使用假数据进行前端测试 - 正常情况下这里应该验证令牌
      try {
        // 从本地存储获取用户数据
        final savedUser = await _storageService.getUser();
        
        if (savedUser != null) {
          _user = savedUser;
          print('已加载用户: ${_user?.id}, ${_user?.username}');
          _status = AuthStatus.authenticated;
        } else {
          _status = AuthStatus.unauthenticated;
        }
      } catch (e) {
        // 出错则清除本地存储
        await _storageService.clearAll();
        _status = AuthStatus.unauthenticated;
      }
    } catch (e) {
      _error = e.toString();
      _status = AuthStatus.error;
    }
    
    notifyListeners();
  }
  
  // 登录
  Future<bool> login(String usernameOrEmail, String password, {bool forceMock = true}) async {
    try {
      _status = AuthStatus.authenticating;
      _error = null;
      notifyListeners();
      
      // 调用API登录
      final response = await _apiService.login(usernameOrEmail, password, forceMock: forceMock);
      
      // 验证响应数据
      if (response.containsKey('token') && response.containsKey('_id')) {
        // 从响应中提取用户数据
        final userId = response['_id'].toString();
        
        final user = User(
          id: userId,
          username: response['username'] ?? '',
          email: response['email'] ?? '',
          avatar: response['avatar'] ?? '',
          bio: response['bio'] ?? '这是我的个人简介',
          isOnline: true,
          lastSeen: DateTime.now(),
        );
        
        _user = user;
        _status = AuthStatus.authenticated;
        
        // 保存用户信息和登录状态
        await _storageService.saveUser(user);
        await _storageService.setLoggedIn(true);
        
        // 记录用户ID，确保其正确设置
        print('用户登录成功，ID: ${user.id}, 用户名: ${user.username}');
        
        notifyListeners();
        return true;
      } else {
        throw Exception('登录成功但服务器返回数据格式不正确');
      }
    } catch (e) {
      print('登录出错: $e');
      _error = e.toString();
      _status = AuthStatus.error;
      notifyListeners();
      return false;
    }
  }
  
  // 注册
  Future<bool> register(String username, String email, String password, {bool forceMock = false}) async {
    try {
      _status = AuthStatus.authenticating;
      _error = null;
      notifyListeners();
      
      // 调用API注册
      final response = await _apiService.register(username, email, password, forceMock: forceMock);
      
      // 验证响应数据
      if (response.containsKey('token') && response.containsKey('_id')) {
        // 从响应中提取用户数据
        final userId = response['_id'].toString();
        
        final user = User(
          id: userId,
          username: response['username'] ?? '',
          email: response['email'] ?? '',
          avatar: response['avatar'] ?? '',
          bio: response['bio'] ?? '这是我的个人简介',
          isOnline: true,
          lastSeen: DateTime.now(),
        );
        
        _user = user;
        _status = AuthStatus.authenticated;
        
        // 保存用户信息和登录状态
        await _storageService.saveUser(user);
        await _storageService.setLoggedIn(true);
        
        // 记录用户ID，确保其正确设置
        print('用户注册成功，ID: ${user.id}, 用户名: ${user.username}');
        
        notifyListeners();
        return true;
      } else {
        throw Exception('注册成功但服务器返回数据格式不正确');
      }
    } catch (e) {
      print('注册出错: $e');
      _error = e.toString();
      _status = AuthStatus.error;
      notifyListeners();
      return false;
    }
  }
  
  // 登出
  Future<void> logout() async {
    _status = AuthStatus.unauthenticated;
    _user = null;
    
    // 清除本地存储
    await _storageService.clearAll();
    
    notifyListeners();
  }
  
  // 检查认证状态
  Future<void> checkAuth({bool forceMockData = false}) async {
    try {
      print('开始检查用户认证状态...');
      
      if (forceMockData) {
        print('强制使用模拟数据模式');
        _status = AuthStatus.unauthenticated;
        notifyListeners();
        return;
      }
      
      final isLoggedIn = await _storageService.isLoggedIn();
      print('存储服务返回的登录状态: $isLoggedIn');
      
      if (isLoggedIn) {
        print('用户已登录，尝试加载用户信息...');
        await _loadUser();
        print('用户信息加载完成: ${_user?.id}, ${_user?.username}, 认证状态=$_status');
      } else {
        print('用户未登录，设置未认证状态');
        _status = AuthStatus.unauthenticated;
        notifyListeners();
      }
    } catch (e) {
      print('认证状态检查出错: $e');
      _error = e.toString();
      _status = AuthStatus.unauthenticated;
      notifyListeners();
    }
  }
  
  // 更新用户信息
  Future<void> updateUserInfo({String? username, String? bio, String? avatar}) async {
    try {
      if (_user == null) return;
      
      // 准备更新数据
      final data = {
        'username': username,
        'bio': bio,
        'avatar': avatar,
      };
      
      // 过滤掉null值
      final filteredData = Map<String, dynamic>.from(data)
        ..removeWhere((key, value) => value == null);
      
      // 调用API更新用户信息
      final response = await _apiService.updateUserProfile(filteredData);
      
      // 创建更新后的用户对象
      User updatedUser = User(
        id: _user!.id,
        username: response['username'] ?? _user!.username,
        email: response['email'] ?? _user!.email,
        avatar: response['avatar'] ?? _user!.avatar,
        bio: response['bio'] ?? _user!.bio,
        isOnline: _user!.isOnline,
        lastSeen: _user!.lastSeen,
      );
      
      _user = updatedUser;
      await _storageService.saveUser(updatedUser);
      
      notifyListeners();
    } catch (e) {
      _error = e.toString();
      notifyListeners();
    }
  }
}